package com.v1.video.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.BaseInfo;
import com.v1.video.domain.MyloginVcodeOfForgetEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.engine.RequestEngine;
import com.v1.video.exception.NetException;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.pay.MD5;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.widgets.MyDialog;

import org.json.JSONException;

public class SettingForget2Activity extends BaseActivity implements
		OnClickListener {

	private EditText editText_phone;
//	private TextView textView_PhoneNum;
	private String phoneNum;
	private ProgressDialog progDialog;
	private TextView txtTitle;
	private String password = "";
	private Button btnSure;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_login_forget2);
	}

	@Override
	protected void initView() {
		editText_phone = (EditText) findViewById(R.id.editText_phone);
//		textView_PhoneNum = (TextView) findViewById(R.id.tv_phoneNum);
		resendButton = (Button) findViewById(R.id.button_resend);
		txtTitle = (TextView) findViewById(R.id.tv_title);
		 btnSure = (Button)findViewById(R.id.forget_btn_sure);
//		((TextView) findViewById(R.id.tv_right)).setText("下一 步");
	}

	@Override
	protected void initData() {
		txtTitle.setText(getResources().getString(
				R.string.setting_login_forget));
		Intent intent = getIntent();
		phoneNum = intent.getStringExtra("phoneNum");
		password = intent.getStringExtra("password");
//		textView_PhoneNum.setText("" + phoneNum);
		((TextView) findViewById(R.id.tv_phoneNum2)).setText(phoneNum);
		btnSure.setEnabled(false);
		resendThread();
	}

	@Override
	protected void setListener() {
//		findViewById(R.id.tv_right).setVisibility(View.VISIBLE);
		findViewById(R.id.forget_btn_sure).setOnClickListener(this);
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		 editText_phone.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					// TODO Auto-generated method stub
					int length = editText_phone.getText().toString().length();
					if(length <= 0){
						btnSure.setEnabled(false);
					}else{
						btnSure.setEnabled(true);
					}
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}
			});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.forget_btn_sure:
		case R.id.tv_right:
			String editVcode = editText_phone.getText().toString();
			if (editVcode == null || editVcode.equals("")) {
				Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
			} else {
//				sendVcode(phoneNum, editVcode, Constant.GET_VCODE_FORGET + "");
				sendVcode(phoneNum, editVcode);
			}
			break;
		case R.id.button_resend:
			// getVcode(phoneNum);
			RequestEngine request = new RequestEngine();
			request.getVcode(SettingForget2Activity.this, phoneNum, password,
					handler, STATE_GET_VCODE_SUCCESS, STATE_GET_VCODE_FAIL);
			resendThread();
			break;
		}

	}

	// 重新获取激活码相关

	private Button resendButton;
	private static final long INTERVAL_TIME = 60000;
	private final int STATE_GET_VCODE_SUCCESS = 0X00004;
	private final int STATE_GET_VCODE_FAIL = 0X00005;
	private final int STATE_SEND_VCODE_SUCCESS = 0X00006;
	private final int STATE_SEND_VCODE_FAIL = 0X00007;
	private final int STATE_SEND_KEY_SUCCESS = 0X00008;
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {

			case 0:
//				resendButton.setText(msg.arg1 + "秒后可获取新验证码");				
				resendButton.setText(msg.arg1 + "S");
				break;
			case 1:
				resendButton.setEnabled(true);
				resendButton.setText("重新发送");
				resendButton.setClickable(true);
				resendButton.setOnClickListener(SettingForget2Activity.this);
				break;
			case STATE_GET_VCODE_SUCCESS:
				break;
			case STATE_GET_VCODE_FAIL:
				break;
			case STATE_SEND_VCODE_SUCCESS:
				
				Intent intent = new Intent(
						SettingForget2Activity.this,
						SettingForget3Activity.class);

				intent.putExtra("phoneNum", phoneNum);
				intent.putExtra("key",(String)msg.obj);
				startActivity(intent);
				SettingForget2Activity.this.finish();
//				sendKey(phoneNum,(String)msg.obj);
				break;
			case STATE_SEND_VCODE_FAIL:
				break;
			case STATE_SEND_KEY_SUCCESS:
				createDialog();
				break;
			}

		}

	};

	private void resendThread() {
		resendButton.setClickable(false);
		resendButton.setEnabled(false);
//		resendButton.setBackgroundResource(R.drawable.button_normal);
		resendButton.setOnClickListener(null);
//		resendButton.setTextColor(getResources().getColor(R.color.dark_gray));

		new Thread() {

			public void run() {

				long startTime = System.currentTimeMillis();

				while (System.currentTimeMillis() - startTime < INTERVAL_TIME) {

					Message msg = new Message();
					msg.what = 0;
					msg.arg1 = (int) ((INTERVAL_TIME
							- System.currentTimeMillis() + startTime) / 1000);
					handler.sendMessage(msg);
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				;

				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}

		}.start();

	}

	// 获取验证码

	/**
	 * 获取验证码线程
	 * 
	 * @param phoneNum
	 */
	private void getVcode(final String phoneNum) {

		new AsyncTask<Void, Void, BaseInfo>() {

			@Override
			protected BaseInfo doInBackground(Void... params) {
				// TODO Auto-generated method stub
				BaseInfo baseInfo = null;
				try {
					baseInfo = new NetEngine().getVcode(phoneNum,
							Constant.GET_VCODE_FORGET + "");
				} catch (NetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return baseInfo;
			}

			@Override
			protected void onPostExecute(BaseInfo result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);

			}

		}.execute();

	}
	
	/**
	 * 修改密码：发送key
	 * @param phoneNum
	 * @param vcode
	 */
	private void sendKey(final String phoneNum, final String cdkey) {
		progDialog = Utils.getProgressDialog(SettingForget2Activity.this,"请稍候");
//		progDialog = ProgressDialog.show(this, null, "请稍候", true, false);
		String key = Constant.getUserCheckKey(phoneNum);
		key = MD5.getMessageDigest(key);
		String url = V1VideoHttpApi.GET_MODIFY_OF_PWD_FORGET() + "&devid="
				+ Constant.DEVICEID + "&key=" + key;
		
		Logger.i(TAG, "忘记密码的：带验证 码修改密码Url =" + url);
		ParamList list = new ParamList();
		list.add(new Parameter("username", phoneNum));
		list.add(new Parameter("cdkey", cdkey));
		RequestManager.getInstance().postRequest(SettingForget2Activity.this, url, list,
				MyloginVcodeOfForgetEntity.class, 0, "SettingForget2Activity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						if(progDialog != null){
							progDialog.dismiss();
						}
						progDialog = null;
						if (object != null) {
							MyloginVcodeOfForgetEntity entity = (MyloginVcodeOfForgetEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								// ToastAlone.showToast(SettingForget1Activity.this,
								// "未知错误", Toast.LENGTH_SHORT);
								return;
							} else if (!header.getStatus().equals("1")) {

								// ToastAlone.showToast(SettingForget1Activity.this,
								// header.getMessage(), Toast.LENGTH_SHORT);
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {
									if (entity.getBody().getData().getStatus()
											.equals("1")) {
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = STATE_SEND_KEY_SUCCESS;
											msg.obj = entity.getBody().getData().getKey();
											handler.sendMessage(msg);
										}

									} else {
										ToastAlone.showToast(SettingForget2Activity.this, entity
												.getBody().getData()
												.getMessage(),
												Toast.LENGTH_SHORT);
									}

								} else {
									// toast(header.getMessage());
								}
							} else {
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						if(progDialog != null){
							progDialog.dismiss();
						}
						progDialog = null;
					}
				});
	}


	/**
	 * 校验：验证码
	 * @param phoneNum
	 * @param vcode
	 */
	private void sendVcode(final String phoneNum, final String vcode) {
		progDialog = Utils.getProgressDialog(SettingForget2Activity.this,"请稍候");
//		progDialog = ProgressDialog.show(this, null, "请稍候", true, false);
		String key = Constant.getUserCheckKey(phoneNum);
		key = MD5.getMessageDigest(key);
		String url = V1VideoHttpApi.GET_VCODE_OF_CHECK() + "&devid="
				+ Constant.DEVICEID + "&key=" + key;
		
		Logger.i(TAG, "忘 记密码发送验证码：Url =" + url);
		ParamList list = new ParamList();
		list.add(new Parameter("username", phoneNum));
		list.add(new Parameter("code", vcode));
		RequestManager.getInstance().postRequest(SettingForget2Activity.this, url, list,
				MyloginVcodeOfForgetEntity.class, 0, "Settingforget2Activity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						if(progDialog != null){
							progDialog.dismiss();
						}
						progDialog = null;
						if (object != null) {
							MyloginVcodeOfForgetEntity entity = (MyloginVcodeOfForgetEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								// ToastAlone.showToast(SettingForget1Activity.this,
								// "未知错误", Toast.LENGTH_SHORT);
								return;
							} else if (!header.getStatus().equals("1")) {

								// ToastAlone.showToast(SettingForget1Activity.this,
								// header.getMessage(), Toast.LENGTH_SHORT);
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {
									if (entity.getBody().getData().getStatus()
											.equals("1")) {
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = STATE_SEND_VCODE_SUCCESS;
											msg.obj = entity.getBody().getData().getKey();
											handler.sendMessage(msg);
										}

									} else {
										ToastAlone.showToast(SettingForget2Activity.this, entity
												.getBody().getData()
												.getMessage(),
												Toast.LENGTH_SHORT);
									}

								} else {
									// toast(header.getMessage());
								}
							} else {
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						if(progDialog != null){
							progDialog.dismiss();
						}
						progDialog = null;
					}
				});
	}

	// 发送验证码相关

	private void sendVcode(final String phoneNum, final String vcode,
			final String isexist) {

		progDialog = ProgressDialog.show(this, null, "请稍候", true, false);

		new AsyncTask<Void, Void, BaseInfo>() {

			@Override
			protected BaseInfo doInBackground(Void... params) {
				// TODO Auto-generated method stub

				BaseInfo baseInfo = null;
				try {
					// baseInfo = new NetEngine().sendVcode(phoneNum, vcode,
					// isexist);
					baseInfo = new NetEngine().sendVcodeWithPassword(phoneNum,
							vcode, isexist, password);

				} catch (NetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				progDialog.dismiss();
				progDialog = null;
				return baseInfo;
			}

			@Override
			protected void onPostExecute(BaseInfo result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);

				if (result != null) {
					if (result != null && result.getCode().equals("1")) {
						// Intent intent_yanzheng = new
						// Intent(SettingForget2Activity.this,
						// SettingForget3Activity.class);
						// intent_yanzheng.putExtra("phoneNum", phoneNum);
						// intent_yanzheng.putExtra("userId",
						// result.getUserId());
						// startActivity(intent_yanzheng);
						// finish();
						createDialog();
					} else {
						Toast.makeText(SettingForget2Activity.this,
								result.getMsg(), Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(SettingForget2Activity.this, "验证失败",
							Toast.LENGTH_SHORT).show();
				}

			}

		}.execute();

	}

	private void createDialog() {

		final MyDialog dialog = Utility.createMyDialog(this,
				R.style.dialog_custom, R.layout.dialog_title_done);
		((TextView) dialog.findViewById(R.id.tv_dialog_title))
				.setText("密码修改成功");
		((TextView) dialog.findViewById(R.id.tv_dialog_content))
				.setText("下次登录请使用新密码");
		TextView ok = (TextView) dialog.findViewById(R.id.tv_dialog_ok);
		ok.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				finish();
			}
		});
		dialog.show();

	}

}
